package com.ham.mud.commands.spells;

import com.ham.mud.ServerConnection;
import com.ham.mud.TargetableService;
import com.ham.mud.commands.PlayerCommand;

import java.util.List;

/**
 * Created by hlucas on Jun 27, 2011 at 12:52:51 PM
 */
public class SpellCommand extends PlayerCommand {
    @Override
    public void execute(ServerConnection connection, String[] params) {
        if(params.length == 0) {
            connection.printSolo("Cast what?");
            return;
        }

        StringBuilder allParams = new StringBuilder();
        for(String s : params) {
            allParams.append(s).append(" ");
        }
        String allParamsString = allParams.toString().trim();
        String spellString = null;
        String target = null;
        if(allParamsString.contains("'")) {
            int firstIndex = allParamsString.indexOf("'");
            int lastIndex = allParamsString.indexOf("'", firstIndex + 1);
            if(lastIndex >= 0) {
                spellString = allParamsString.substring(firstIndex + 1, lastIndex);
                int splitLength = spellString.split(" ").length;
                if(params.length > splitLength + 1) {
                    target = params[splitLength + 1];
                }
            }
        }

        if(spellString == null) {
            spellString = params[0];
            if(params.length > 1) {
                target = params[1];
            }
        }

        List<Spell> spells = connection.getPlayer().getSpells();
        Spell spell = (Spell) TargetableService.findTarget(spellString, spells);
        if(spell == null) {
            connection.printSolo("You don't know that spell.");
            return;
        }

        spell.castSpell(connection, target);
    }

    @Override
    protected String getCommandName() {
        return "cast";
    }
}
